#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

#define MAX_NUM 1024
#define MAX_STR 8

void substring(char* argv[], char* buffer)
{
    int i = 0;
    argv[i++] = strtok(buffer," ");
    if(argv[0] != nullptr && strcmp(argv[0],"ls") == 0)
        argv[i++] = (char*)"--color=auto";
    while(argv[i++] = strtok(nullptr," "));
}


void shell_work()
{



// #ifdef _DEBUG_
//     for(int i = 0; argv[i]; i++)
//     {
//         printf("argv[%d] = %s\n", i,argv[i]);
//     }
// #endif
}

static int lastExit_Code;
static int lastSig;


int main()
{
    //父进程派发子进程去完成指定命令
    while(1)
    {
        char buffer[MAX_NUM];
        cout << "请输入指令> ";
        fgets(buffer,sizeof(buffer)-1,stdin);
        buffer[strlen(buffer)-1] = 0; // 'n' -> '\0'

        //切割子串
        char* argv[MAX_STR];
        substring(argv,buffer);

#ifdef _DEBUG_
    for(int i = 0; argv[i]; i++)
    {
        printf("argv[%d] = %s\n", i,argv[i]);
    }
#endif
        
        //内建命令
        if(argv[0] && strcmp(argv[0],"cd") == 0)
        {
            if(argv[1])     chdir(argv[1]);
            continue;
        }
        if(argv[0] && strcmp(argv[0],"echo") == 0)
        {
            if(argv[1] && strcmp(argv[1],"$?") == 0)
                cout << lastExit_Code << endl;
            else
                cout << argv[1] << endl;
            
            continue;
        }


        pid_t id = fork();
        if(id == 0)
        {
            //child
            execvp(argv[0],argv);
            exit(1);
        }
        else 
        {
            //parent
            //等待子进程
            int status = 0;
            waitpid(id,&status,0);//阻塞等待
            lastExit_Code = ((status>>8)&0xff);
            lastSig = (status&0x7f);
        }
    }


    return 0;
}